package com.bigfire.dtm.shared.common;

import com.bigfire.dtm.shared.constant.Constants;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.Value;

import java.util.List;
import java.util.Optional;

/**
 * 分页处理
 * @author damon S. on 16/8/30.
 */
@Getter
@NoArgsConstructor
public final class Pagination<T> {
    /***分页信息*/
    private PageInfo pageInfo;

    @Setter
    @JsonInclude(Include.NON_EMPTY)
    private List<T> results;

    public Pagination(Long pageIndex, Long pageSize,
                      Long totalSize, List<T> results) {
        this.results = results;
        this.pageInfo = new PageInfo(pageIndex, pageSize, totalSize);
    }

    @Value
    public static class PageInfo {
        /***当前页码*/
        Long pageIndex;

        /***每页数量*/
        Long pageSize;

        /***数据总数*/
        Long totalSize;

        /***总页数*/
        public Long getTotalPage() {
            return Double.valueOf(Math.ceil(totalSize / (pageSize * 1.0d))).longValue();
        }

        private PageInfo(Long pageIndex, Long pageSize, Long totalSize) {
            this.totalSize = Optional.ofNullable(totalSize).orElse(Constants.LONG_ZERO);
            this.pageSize = Optional.ofNullable(pageSize).orElse(Constants.LONG_PAGE_SIZE);
            Long totalPages = getTotalPage();
            this.pageIndex = pageIndex > totalPages ? totalPages : pageIndex;
        }
    }
}
